package lew.bing.tom;

import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.connector.Connector;
import org.apache.catalina.startup.Tomcat;

import javax.servlet.ServletContext;
import java.io.File;


@Slf4j
public class HelloWorld {

    public static void main(String[] args) throws LifecycleException {
        final Tomcat tomcat = new Tomcat();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                tomcat.destroy();
            } catch (LifecycleException e) {
                e.printStackTrace();
            }
        }));
        final String baseDir = new File("web").getAbsolutePath();
        tomcat.setBaseDir(baseDir);
        tomcat.setHostname("localhost");
        tomcat.setPort(8090);
        final Connector connector = tomcat.getConnector();
        System.out.println("连接器设置完成: " + connector);
        Context ctx = tomcat.addContext("", /*{webapps}/~*/ "/ROOT");
        final ServletContext servletContext = ctx.getServletContext();
        ServletTemplateEngineProvider engineProvider = new ServletTemplateEngineProvider(servletContext);
        engineProvider.setPrefix("/html");
        engineProvider.setScriptRoot(baseDir + "/groovy");
        Tomcat.addServlet(ctx, "globalServlet", new GlobalServlet(new ThymeleafHtmlHandler(engineProvider)));
        ctx.addServletMappingDecoded("/","globalServlet");

        tomcat.start();
        System.out.println("tomcat 已启动");
        tomcat.getServer().await();
    }

}
